package course.controller;

import cn.hutool.crypto.digest.DigestUtil;
import course.pojo.entity.Admin;
import course.service.AdminService;
import course.service.impl.AdminServiceImpl;
import org.apache.commons.lang.StringUtils;

import javax.servlet.DispatcherType;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * 修改管理员的密码，头像
 *
 * @author HLF
 * @date 2022/7/5 10:37
 */
@WebServlet("/admin/updateController")
@MultipartConfig
public class AdminUpdateController extends HttpServlet {
    private AdminService adminService = new AdminServiceImpl();

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");

        HttpSession session = req.getSession();
        Admin admin = (Admin) session.getAttribute("auser");

        Part atar = req.getPart("atar");
        if (atar != null) {
            String submittedFileName = atar.getSubmittedFileName();
            String fileType = submittedFileName.substring(submittedFileName.indexOf("."));
            String newName = admin.getAid() + fileType;

            String path = getServletContext().getRealPath("/atar/" + newName);
            atar.write(path);//1.更新服务器目录(tomcat编译后目录)

            admin.setAtar("atar/" + newName);
        }

        String apassword2 = req.getParameter("apassword2");
        if (StringUtils.isNotBlank(apassword2)) {
            String pass = DigestUtil.bcrypt(apassword2);
            admin.setApassword(pass);
        }
        int i = adminService.updateById(admin);

        if (i > 0) {
            session.setAttribute("auser", admin);
            resp.sendRedirect(req.getContextPath() + "/admin_center.jsp");
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}
